cmake_minimum_required(VERSION 3.16)

cmake_policy(SET CMP0071 NEW)

# 支持通过命令行参数覆盖版本号
# 用法: cmake -DPROJECT_VERSION_OVERRIDE="2.8.0" ..
if(NOT DEFINED PROJECT_VERSION_OVERRIDE)
    set(PROJECT_VERSION_OVERRIDE "2.7.2")
endif()

project(LongImageReader VERSION ${PROJECT_VERSION_OVERRIDE} LANGUAGES CXX)

# Qt: rely on system/ENV discovery. On Windows, allow an overridable QT_ROOT.   
if(WIN32)
    if(NOT DEFINED QT_ROOT)
        # 优先使用MinGW版本，如果没有则使用MSVC版本
        if(EXISTS "C:/Qt/6.9.2/mingw_64")
            set(QT_ROOT "C:/Qt/6.9.2/mingw_64" CACHE PATH "Qt root path on Windows")
        elseif(EXISTS "C:/Qt/6.9.2/msvc2019_64")
            set(QT_ROOT "C:/Qt/6.9.2/msvc2019_64" CACHE PATH "Qt root path on Windows")
        else()
            set(QT_ROOT "C:/Qt/6.9.2/mingw_64" CACHE PATH "Qt root path on Windows")
        endif()
    endif()
    list(APPEND CMAKE_PREFIX_PATH "${QT_ROOT}")
endif()


set(CMAKE_CXX_STANDARD 17)
set(CMAKE_CXX_STANDARD_REQUIRED ON)
set(CMAKE_CXX_EXTENSIONS OFF)

if(NOT CMAKE_BUILD_TYPE)
    set(CMAKE_BUILD_TYPE Release CACHE STRING "Build type" FORCE)
endif()

# 显示构建配置信息
message(STATUS "=== 构建配置信息 ===")
message(STATUS "项目名称: ${PROJECT_NAME}")
message(STATUS "版本: ${PROJECT_VERSION}")
message(STATUS "构建类型: ${CMAKE_BUILD_TYPE}")
message(STATUS "===================")

set(CMAKE_AUTOMOC ON)
set(CMAKE_AUTORCC ON)
set(CMAKE_AUTOUIC ON)

find_package(Qt6 REQUIRED COMPONENTS
        Core
        Gui
        Widgets
        PrintSupport
        Network
)

# Qt6::StateMachine 和 Qt6::Pdf 是可选的
find_package(Qt6 COMPONENTS StateMachine QUIET)
if(Qt6StateMachine_FOUND)
    message(STATUS "Found Qt6::StateMachine module")
else()
    message(STATUS "Qt6::StateMachine not found, some advanced features may not work")
endif()

# Qt6::Pdf 是可选的
find_package(Qt6 COMPONENTS Pdf QUIET)
if(Qt6Pdf_FOUND)
    message(STATUS "Found Qt6::Pdf module (optional)")
else()
    message(STATUS "Qt6::Pdf not found, using alternative PDF handling")
endif()

# PDF support using Poppler library (cross-platform)
option(USE_POPPLER_LIBRARY "Enable PDF support with Poppler library" ON)

# Windows: 使用mingw64-poppler目录（包含完整的库文件）
set(POPPLER_ROOT "${CMAKE_CURRENT_SOURCE_DIR}/mingw64-poppler" CACHE PATH "Path to Poppler installation (Windows installed)")

# Detect Poppler
set(POPPLER_FOUND FALSE)
if(USE_POPPLER_LIBRARY)
    if(WIN32)
        if(EXISTS "${POPPLER_ROOT}/include/poppler/cpp/poppler-document.h")
            set(POPPLER_INCLUDE_DIR "${POPPLER_ROOT}/include")
            set(POPPLER_LIB_DIR "${POPPLER_ROOT}/lib")
            set(POPPLER_FOUND TRUE)
            message(STATUS "Poppler library found at: ${POPPLER_ROOT}")
        endif()
    else()
        find_package(PkgConfig QUIET)
        if(PkgConfig_FOUND)
            pkg_check_modules(POPPLER_CPP QUIET IMPORTED_TARGET poppler-cpp)
            if(POPPLER_CPP_FOUND)
                set(POPPLER_FOUND TRUE)
                message(STATUS "Found poppler-cpp via pkg-config: ${POPPLER_CPP_VERSION}")
                message(STATUS "poppler-cpp include dirs: ${POPPLER_CPP_INCLUDE_DIRS}")
            endif()
        endif()
    endif()
endif()

if(POPPLER_FOUND)
    message(STATUS "PDF support enabled using Poppler library")
else()
    message(STATUS "Poppler library not found, falling back to external tools")
    message(STATUS "To get full PDF functionality, install one of:")
    message(STATUS "  - Poppler with C++ bindings (poppler-cpp)")
    message(STATUS "  - ImageMagick (convert)")
    message(STATUS "  - Ghostscript (gs)")
endif()

add_library(libb2 STATIC
        ${CMAKE_CURRENT_SOURCE_DIR}/libb2-0.98.1/src/blake2b.c
        ${CMAKE_CURRENT_SOURCE_DIR}/libb2-0.98.1/src/blake2bp.c
        ${CMAKE_CURRENT_SOURCE_DIR}/libb2-0.98.1/src/blake2s.c
        ${CMAKE_CURRENT_SOURCE_DIR}/libb2-0.98.1/src/blake2sp.c
)

target_include_directories(libb2 PUBLIC
        ${CMAKE_CURRENT_SOURCE_DIR}/libb2-0.98.1/src
)

if(WIN32)
    set(APP_ICON_RESOURCE_WINDOWS "${CMAKE_CURRENT_SOURCE_DIR}/app.rc")
endif()

set(SOURCES
    main.cpp
    crashhandler.cpp
    pathmanager.cpp
    systemconfig.cpp
    systemconfigdialog.cpp
    systemconfigmanager.cpp
    configmanager.cpp
        application.cpp
        imageprocessor.cpp
        pageview.cpp
        thumbnailview.cpp
        virtualthumbnailview.cpp
        progressdialog.cpp
        splashscreen.cpp
        outputsettings.cpp
        streamingexportmanager.cpp
        singlefileexporttask.cpp
        statusbarmanager.cpp
        exportstatemanager.cpp
        applicationstatemanager.cpp
        fileprogressdisplay.cpp
        outputpreviewwidget.cpp
        zoomablepreview.cpp
        modernui.cpp
        updatechecker.cpp
        # simple_renderer.cpp - 已移除，使用UnifiedPageRenderer
                memorycachemanager.cpp
        unifiedcachemanager.cpp
        preloadcontroller.cpp
        backgroundloader.cpp
        customfileitem.cpp
        customfilelistwidget.cpp
        virtuallistmanager.cpp  # 虚拟化列表管理器
        # customfilelistcoordinator.cpp  # Martin Fowler重构：已移除
        customfilebrowser.cpp
        dragcontext.cpp
        filelistordermanager.cpp
        filelistcontextmenu.cpp
        naturalsortcomparator.cpp
        fileinforepository.cpp
        unifiedfileinfo.cpp
        cachepathinfo.cpp
        minimalmemorymanager.cpp
        ${APP_ICON_RESOURCE_WINDOWS}
        resources.qrc
        translations.qrc
        batchenhancepanel.cpp
        mainwindow.cpp
        licensemanager.cpp
        watermark.cpp
        licensedialog.cpp
        fileprocessworker.cpp
        configimpactdetector.cpp
        cacherebuildmanager.cpp
        nextgen_placeholder.cpp
        layoutstatemanager.cpp
        filestatusiconmanager.cpp
        progressicongenerator.cpp
        fileidentitymanager.cpp
        systemresourcemonitor.cpp
        unifiedthreadmanager.cpp
        fileprocessingtask.cpp
        pagerenderer.cpp
        unifieddragdrophandler.cpp
        unifiedpagerenderer.cpp
        settingswidget.cpp
        smartpagenumberselector.cpp
        gridpagenumbersystem.cpp
        # physicalpagenumberrenderer.cpp - 已移除或合并到其他文件
        statusbarformatter.cpp
        # exportstatuscontroller.cpp - Martin Fowler重构：已合并到ExportStateManager
        immediateupdatestrategy.cpp
        batchupdatestrategy.cpp
        dpiservice.cpp
        toastnotification.cpp
        # === Martin Fowler重构：双画布渲染系统 ===
        displaycanvascalculator.cpp
        dualcanvasrenderer.cpp
        virtualcanvasmanager.cpp
        # === 自定义预设管理系统 ===
        presetmanager.cpp
        # === Martin Fowler重构：统一页码管理系统 ===
        pagepositionsystem.cpp
        pagerendercontext.cpp
        globalpagemanager.cpp
        # === 专业精细调整系统 (基于Jony Ive设计理念) ===
        # finetunemagnifier.cpp - 已移除，使用SmartPageNumberSelector内联精细调整
        # === Martin Fowler重构：PageNumberFormatter提取 ===
        pagenumberformatter.cpp
        # === Martin Fowler重构：PageDisplayStrategy策略模式 ===
        pagedisplaystrategy.cpp
        pagedisplaystrategyfactory.cpp
        # === Martin Fowler重构：PageNumberConfigFacade门面模式 ===
        pagenumberconfigfacade.cpp
        # === Martin Fowler重构：PageNumberService服务层 ===
        pagenumberservice.cpp
        # === 图标工厂系统 ===
        IconFactory.cpp
        # === 登录系统 ===
        logindialog.cpp
        userinfodialog.cpp
        apimanager.cpp
        # === 自动更新系统 ===
        versionmanager.cpp
        updatemanager.cpp
        updatedialog.cpp
        systemtraymanager.cpp
        aboutdialog.cpp
        protection.cpp
        # === 代码混淆和安全系统 ===
        codeobfuscation.cpp
        advancedprotection.cpp
        dynamicwatermark.cpp
        # === Token安全管理 ===
        securetokenmanager.cpp
        secureapimanager.cpp
        util.cpp
)

set(HEADERS
        crashhandler.h
        systemconfig.h
        systemconfigdialog.h
        systemconfigmanager.h
        imageprocessor.h
        mainwindow.h
        pageview.h
        thumbnailview.h
        virtualthumbnailview.h
        progressdialog.h
        splashscreen.h
        outputsettings.h
        streamingexportmanager.h
        singlefileexporttask.h
        statusbarmanager.h
        fileprogressdisplay.h
        outputpreviewwidget.h
        modernui.h
        licensemanager.h
        watermark.h
        licensedialog.h
        batchenhancepanel.h
        batchsettings.h
        fileprocessworker.h
        configimpactdetector.h
        cacherebuildmanager.h
        nextgen_placeholder.h
                unifiedcachemanager.h
        memorycachemanager.h
        filestatusiconmanager.h
        progressicongenerator.h
        preloadcontroller.h
        backgroundloader.h
        layoutstatemanager.h
        fileidentitymanager.h
        itask.h
        systemresourcemonitor.h
        unifiedthreadmanager.h
        fileprocessingtask.h
        pagerenderer.h
        unifieddragdrophandler.h
        customfileitem.h
        customfilelistwidget.h
        # customfilelistcoordinator.h  # Martin Fowler重构：已移除
        customfilebrowser.h
        naturalsortcomparator.h
        unifiedfileinfo.h
        cachepathinfo.h
        unifiedpagerenderer.h
        processingsettings.h
        settingswidget.h
        smartpagenumberselector.h
        gridpagenumbersystem.h
        # physicalpagenumberrenderer.h - 已移除或合并到其他文件
        exportprogress.h
        statusbarformatter.h
        # exportstatuscontroller.h - Martin Fowler重构：已合并到ExportStateManager
        statusbarstate.h
        istatusupdatestrategy.h
        immediateupdatestrategy.h
        batchupdatestrategy.h
        dpiservice.h
        toastnotification.h
        # === Martin Fowler重构：双画布渲染系统 ===
        displaycanvascalculator.h
        dualcanvasrenderer.h
        virtualcanvasmanager.h
        # === 自定义预设管理系统 ===
        presetmanager.h
        # === Martin Fowler重构：统一页码管理系统 ===
        pagepositionsystem.h
        pagerendercontext.h
        globalpagemanager.h
        # === 专业精细调整系统 (基于Jony Ive设计理念) ===
        # finetunemagnifier.h - 已移除，使用SmartPageNumberSelector内联精细调整
        # === Martin Fowler重构：PageNumberFormatter提取 ===
        pagenumberformatter.h
        # === Martin Fowler重构：PageDisplayStrategy策略模式 ===
        pagedisplaystrategy.h
        pagedisplaystrategyfactory.h
        # === Martin Fowler重构：PageNumberConfigFacade门面模式 ===
        pagenumberconfigfacade.h
        # === Martin Fowler重构：PageNumberService服务层 ===
        pagenumberservice.h
        # === 图标工厂系统 ===
        IconFactory.h
        # === 登录系统 ===
        logindialog.h
        userinfodialog.h
        # === 自动更新系统 ===
        versionmanager.h
        updatemanager.h
        updatedialog.h
        systemtraymanager.h
        aboutdialog.h
        protection.h
        # === 代码混淆和安全系统 ===
        codeobfuscation.h
        advancedprotection.h
        dynamicwatermark.h
        # === Token安全管理 ===
        securetokenmanager.h
        secureapimanager.h
        util.h
)

message(STATUS "Resource BASE path: ${CMAKE_BINARY_DIR}")

add_executable(LimeReader
        ${SOURCES}
        ${HEADERS}
        ${QM_FILES}
        ${RESOURCES}
)

if(WIN32)
    # 在Debug模式下添加控制台窗口以查看qDebug输出
    if(CMAKE_BUILD_TYPE STREQUAL "Debug")
        set_target_properties(LimeReader PROPERTIES
                WIN32_EXECUTABLE FALSE  # 显示控制台窗口
        )
    else()
        set_target_properties(LimeReader PROPERTIES
                WIN32_EXECUTABLE TRUE   # 隐藏控制台窗口
        )
    endif()
endif()

# macOS app bundle configuration
if(APPLE)
    set_target_properties(LimeReader PROPERTIES
        MACOSX_BUNDLE TRUE
        MACOSX_BUNDLE_BUNDLE_NAME "LimeReader"
        MACOSX_BUNDLE_GUI_IDENTIFIER "com.limereader.app"
        MACOSX_BUNDLE_BUNDLE_VERSION "${PROJECT_VERSION}"
        MACOSX_BUNDLE_SHORT_VERSION_STRING "${PROJECT_VERSION}"
        MACOSX_BUNDLE_LONG_VERSION_STRING "${PROJECT_VERSION}"
        MACOSX_BUNDLE_INFO_STRING "LimeReader - Long Image Reader"
        MACOSX_BUNDLE_COPYRIGHT "Copyright (c) 2024 LimeReader"
        RUNTIME_OUTPUT_DIRECTORY_RELEASE "${CMAKE_BINARY_DIR}/bin/Release"
        RUNTIME_OUTPUT_DIRECTORY_DEBUG "${CMAKE_BINARY_DIR}/bin/Debug"
        # 设置 rpath 以便应用可以找到内部的 Frameworks
        BUILD_RPATH "@executable_path/../Frameworks"
        INSTALL_RPATH "@executable_path/../Frameworks"
        BUILD_WITH_INSTALL_RPATH TRUE
    )

    # Set the icon file for macOS
    if(EXISTS "${CMAKE_SOURCE_DIR}/icons/macos.icns")
        set_target_properties(LimeReader PROPERTIES
            MACOSX_BUNDLE_ICON_FILE "macos.icns"
        )
        # Copy the icon file to the Resources folder
        add_custom_command(TARGET LimeReader POST_BUILD
            COMMAND ${CMAKE_COMMAND} -E make_directory
            "$<TARGET_FILE_DIR:LimeReader>/../Resources"
            COMMAND ${CMAKE_COMMAND} -E copy_if_different
            "${CMAKE_SOURCE_DIR}/icons/macos.icns"
            "$<TARGET_FILE_DIR:LimeReader>/../Resources/macos.icns"
            COMMENT "Copying app icon to bundle..."
        )
    endif()

    # 临时禁用代码签名以解决运行问题
    set_target_properties(LimeReader PROPERTIES
        XCODE_ATTRIBUTE_CODE_SIGN_IDENTITY "-"
        XCODE_ATTRIBUTE_CODE_SIGNING_REQUIRED "NO"
        XCODE_ATTRIBUTE_CODE_SIGNING_ALLOWED "NO"
    )
endif()

target_include_directories(LimeReader PRIVATE
        ${CMAKE_CURRENT_SOURCE_DIR}
        ${CMAKE_CURRENT_SOURCE_DIR}/libb2-0.98.1/src
)

# 添加调试构建类型选项
option(ENABLE_ASAN "Enable AddressSanitizer for debugging" OFF)
option(ENABLE_TSAN "Enable ThreadSanitizer for debugging" OFF)

target_compile_definitions(LimeReader PRIVATE
        $<$<CONFIG:Debug>:QT_DEBUG>
        $<$<CONFIG:Release>:QT_NO_DEBUG>
        $<$<CONFIG:Release>:QT_NO_DEBUG_OUTPUT>
        $<$<CONFIG:Release>:QT_NO_WARNING_OUTPUT>
        $<$<CONFIG:Release>:QT_NO_INFO_OUTPUT>
)

# AddressSanitizer和ThreadSanitizer支持
if(ENABLE_ASAN)
    message(STATUS "启用AddressSanitizer进行内存错误检测")
    target_compile_options(LimeReader PRIVATE -fsanitize=address -fno-omit-frame-pointer -g)
    target_link_options(LimeReader PRIVATE -fsanitize=address)
endif()

if(ENABLE_TSAN)
    message(STATUS "启用ThreadSanitizer进行线程错误检测")
    target_compile_options(LimeReader PRIVATE -fsanitize=thread -fno-omit-frame-pointer -g)
    target_link_options(LimeReader PRIVATE -fsanitize=thread)
endif()

# Debug模式下添加更多调试信息
if(CMAKE_BUILD_TYPE STREQUAL "Debug")
    target_compile_options(LimeReader PRIVATE -g -O0 -fno-omit-frame-pointer)
endif()

# Poppler是必须的，直接配置（移除条件检查）
# Add PDF support definitions and libraries
if(WIN32)
        target_include_directories(LimeReader PRIVATE
            "${POPPLER_INCLUDE_DIR}"
            "${POPPLER_INCLUDE_DIR}/poppler"
            "${POPPLER_INCLUDE_DIR}/poppler/cpp"
        )
        target_link_directories(LimeReader PRIVATE "${POPPLER_LIB_DIR}")
        target_link_libraries(LimeReader PRIVATE poppler-cpp poppler)
    else()
        if(TARGET PkgConfig::POPPLER_CPP)
            target_link_libraries(LimeReader PRIVATE PkgConfig::POPPLER_CPP)
            # Ensure headers are reachable with <poppler/cpp/...>
            target_include_directories(LimeReader PRIVATE ${POPPLER_CPP_INCLUDE_DIRS})
            set(_POPPLER_PARENT_INCLUDE_DIRS "")
            foreach(_dir IN LISTS POPPLER_CPP_INCLUDE_DIRS)
                get_filename_component(_parent "${_dir}" DIRECTORY)
                list(APPEND _POPPLER_PARENT_INCLUDE_DIRS "${_parent}")
            endforeach()
            list(REMOVE_DUPLICATES _POPPLER_PARENT_INCLUDE_DIRS)
            target_include_directories(LimeReader PRIVATE ${_POPPLER_PARENT_INCLUDE_DIRS})
        else()
            # Fallback: try typical names
            find_library(POPPLER_CPP_LIB NAMES poppler-cpp)
            if(POPPLER_CPP_LIB)
                target_link_libraries(LimeReader PRIVATE ${POPPLER_CPP_LIB})
            endif()
            # Fallback common include roots (Homebrew)
            if(EXISTS "/opt/homebrew/include/poppler/cpp/poppler-document.h")
                target_include_directories(LimeReader PRIVATE /opt/homebrew/include)
            endif()
            if(EXISTS "/usr/local/include/poppler/cpp/poppler-document.h")
                target_include_directories(LimeReader PRIVATE /usr/local/include)
            endif()
        endif()
    endif()

target_link_libraries(LimeReader PRIVATE
        Qt6::Core
        Qt6::Gui
        Qt6::Widgets
        Qt6::PrintSupport
        Qt6::Network
        libb2
)

# Windows specific libraries
if(WIN32)
    target_link_libraries(LimeReader PRIVATE dbghelp)
endif()

# 只有当可选组件可用时才链接
if(Qt6StateMachine_FOUND)
    target_link_libraries(LimeReader PRIVATE Qt6::StateMachine)
endif()

# Qt6::Pdf 是可选的
if(Qt6Pdf_FOUND)
    target_link_libraries(LimeReader PRIVATE Qt6::Pdf)
endif()


set_target_properties(LimeReader PROPERTIES
        RUNTIME_OUTPUT_DIRECTORY_RELEASE "${CMAKE_BINARY_DIR}/bin/Release"
        RUNTIME_OUTPUT_DIRECTORY_DEBUG "${CMAKE_BINARY_DIR}/bin/Debug"
        RUNTIME_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}/bin/${CMAKE_BUILD_TYPE}"
)

# 统一版本管理系统 - 传递版本号到编译器
# 将CMakeLists.txt中的版本号传递给C++代码
message(STATUS "配置应用版本: ${PROJECT_VERSION}")

# 定义版本号宏，供app_version.h使用
target_compile_definitions(LimeReader PRIVATE
    APP_VERSION="${PROJECT_VERSION}"
    APP_VERSION_MAJOR=${PROJECT_VERSION_MAJOR}
    APP_VERSION_MINOR=${PROJECT_VERSION_MINOR}
    APP_VERSION_PATCH=${PROJECT_VERSION_PATCH}
    APP_VERSION_TWEAK=${PROJECT_VERSION_TWEAK}
)

# 在Release构建时创建版本信息文件
if(CMAKE_BUILD_TYPE STREQUAL "Release")
    # 生成版本信息文件，供构建脚本使用
    configure_file(
        "${CMAKE_CURRENT_SOURCE_DIR}/version_info.json.in"
        "${CMAKE_BINARY_DIR}/version_info.json"
        @ONLY
    )

    message(STATUS "版本信息文件已生成: ${CMAKE_BINARY_DIR}/version_info.json")
endif()

# Copy icons directory (Windows only - macOS uses embedded resources)
if(WIN32)
    add_custom_command(TARGET LimeReader POST_BUILD
            COMMAND ${CMAKE_COMMAND} -E copy_directory
            ${CMAKE_SOURCE_DIR}/icons
            $<TARGET_FILE_DIR:LimeReader>/icons
    )
endif()

# Copy Poppler DLLs if using Poppler library (Windows only)
if(WIN32 AND POPPLER_FOUND)
    add_custom_command(TARGET LimeReader POST_BUILD
            COMMAND ${CMAKE_COMMAND} -E copy_if_different
            "${POPPLER_ROOT}/bin/libpoppler-153.dll"
            "${POPPLER_ROOT}/bin/libpoppler-cpp-2.dll"
            $<TARGET_FILE_DIR:LimeReader>
            COMMENT "Copying Poppler DLLs..."
    )
endif()

# Copy project dynlibs to target directory
if(EXISTS "${CMAKE_CURRENT_SOURCE_DIR}/dynlibs")
    add_custom_command(TARGET LimeReader POST_BUILD
            COMMAND ${CMAKE_COMMAND} -E copy_directory
            "${CMAKE_CURRENT_SOURCE_DIR}/dynlibs"
            $<TARGET_FILE_DIR:LimeReader>
            COMMENT "Copying project dynamic libraries..."
    )
    message(STATUS "Project dynlibs directory found, will copy DLLs to target directory")
else()
    message(STATUS "Project dynlibs directory not found, skipping DLL copy")
endif()


if(WIN32)
    set(QT_DEPLOY_PATH "${QT_ROOT}/bin/windeployqt.exe")

    if(NOT EXISTS ${QT_DEPLOY_PATH})
        message(FATAL_ERROR "windeployqt not found at ${QT_DEPLOY_PATH}")
    endif()

    add_custom_command(TARGET LimeReader POST_BUILD
            COMMAND ${QT_DEPLOY_PATH}
            --verbose 1
            --no-compiler-runtime
            --no-translations
            --no-system-d3d-compiler
            --dir "$<TARGET_FILE_DIR:LimeReader>"
            "$<TARGET_FILE:LimeReader>"
            COMMENT "Deploying Qt dependencies..."
    )
endif()

# macOS deployment with macdeployqt
if(APPLE)
    find_program(MACDEPLOYQT_EXECUTABLE macdeployqt HINTS ${Qt6_DIR}/../../../bin)

    if(MACDEPLOYQT_EXECUTABLE)
        message(STATUS "Found macdeployqt at: ${MACDEPLOYQT_EXECUTABLE}")

        # Create a custom target for deployment
        add_custom_target(deploy_mac
            COMMAND ${MACDEPLOYQT_EXECUTABLE} "$<TARGET_FILE_DIR:LimeReader>/../.." -verbose=2 -codesign=-
            DEPENDS LimeReader
            COMMENT "Deploying Qt libraries to macOS app bundle"
            WORKING_DIRECTORY ${CMAKE_BINARY_DIR}
        )

        # Remove signature after deployment
        add_custom_target(unsign_app
            COMMAND codesign --remove-signature "$<TARGET_FILE_DIR:LimeReader>/../.."
            DEPENDS deploy_mac
            COMMENT "Removing code signature"
            WORKING_DIRECTORY ${CMAKE_BINARY_DIR}
        )

        # Optional: Create DMG
        add_custom_target(create_dmg
            COMMAND ${MACDEPLOYQT_EXECUTABLE} "$<TARGET_FILE_DIR:LimeReader>/../.." -dmg -verbose=2
            DEPENDS LimeReader
            COMMENT "Creating DMG installer"
            WORKING_DIRECTORY ${CMAKE_BINARY_DIR}
        )
    else()
        message(WARNING "macdeployqt not found. Manual deployment may be required.")
    endif()
endif()

# Martin Fowler重构：集成测试程序
add_executable(test_pagenumber_integration
    run_integration_tests.cpp
    pagenumberformatter.cpp
    pagerendercontext.cpp
    pagedisplaystrategy.cpp
    pagedisplaystrategyfactory.cpp
    pagenumberconfigfacade.cpp
    pagenumberservice.cpp
    processingsettings.h
    pagepositionsystem.cpp
    gridpagenumbersystem.cpp
)

target_include_directories(test_pagenumber_integration PRIVATE
    ${CMAKE_CURRENT_SOURCE_DIR}
    ${CMAKE_CURRENT_SOURCE_DIR}/libb2-0.98.1/src
)

target_link_libraries(test_pagenumber_integration PRIVATE
    Qt6::Core
    Qt6::Gui
    Qt6::Widgets
)

set_target_properties(test_pagenumber_integration PROPERTIES
     RUNTIME_OUTPUT_DIRECTORY_RELEASE "${CMAKE_BINARY_DIR}/bin/Release"
    RUNTIME_OUTPUT_DIRECTORY_DEBUG "${CMAKE_BINARY_DIR}/bin/Debug"
    RUNTIME_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}/bin/${CMAKE_BUILD_TYPE}"
)

# 全局页码测试程序（暂时禁用 - 源文件缺失）
# add_executable(test_global_pagenumber
#     test_global_pagenumber.cpp
#     pagenumberformatter.cpp
#     pagerendercontext.cpp
#     processingsettings.h
#     pagepositionsystem.cpp
#     gridpagenumbersystem.cpp
# )
# 
# target_include_directories(test_global_pagenumber PRIVATE
#     ${CMAKE_CURRENT_SOURCE_DIR}
#     ${CMAKE_CURRENT_SOURCE_DIR}/libb2-0.98.1/src
# )
# 
# target_link_libraries(test_global_pagenumber PRIVATE
#     Qt6::Core
#     Qt6::Gui
#     Qt6::Widgets
# )
# 
# set_target_properties(test_global_pagenumber PROPERTIES
#     RUNTIME_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}/bin"
# )

message(STATUS "Source directory: ${CMAKE_CURRENT_SOURCE_DIR}")
message(STATUS "Build directory: ${CMAKE_BINARY_DIR}")